package middleware

import (
	"gin-project/utils"
	"gin-project/utils/errmsg"
	"github.com/dgrijalva/jwt-go"
	"time"
)

// jwt加密的盐
var jwtKey = []byte(utils.JwtKey)

// 需要加密的信息
type UserToken struct {
	jwt.StandardClaims
	UserName string `json:"user_name"`
}

// 获取token
func GetToken(username string) (string, int) {
	duration := time.Duration(utils.JwtExpire)
	user := UserToken{
		StandardClaims: jwt.StandardClaims{
			Issuer:    "xiaolatiao",
			ExpiresAt: time.Now().Add(duration * time.Hour).Unix(),
		},
		UserName: username,
	}

	// 生成token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, user)
	// 使用盐加密token
	tokenStr, err := token.SignedString(jwtKey)
	if err != nil {
		return "", errmsg.TOKEN_GET_FAILED
	}
	return tokenStr, errmsg.SUCCESS
}

// 认证token
func AuthToken(tokenStr string) (*UserToken, int) {
	// 解析token
	token, err := jwt.ParseWithClaims(tokenStr, &UserToken{}, func(token *jwt.Token) (interface{}, error) {
		// 返回加密时用的盐
		return jwtKey, nil
	})
	if err != nil {
		return nil, errmsg.TOKEN_PARSE_FAILED
	}

	user, ok := token.Claims.(*UserToken)
	// 校验token
	if token.Valid && ok {
		return user, errmsg.SUCCESS
	}

	return nil, errmsg.ERROR
}
